package threadDemo;
import java.util.concurrent.atomic.AtomicStampedReference;
/**
 * @author Ajie
 * @date 2023/8/8
 * @function
 *
 * 尽管 t1 线程修改了 atomicStampedRef 的值，但由于版本号的存在，t2 线程的 CAS 操作失败，从而成功地解决了 ABA 问题。
 */
public class Atomic_CAS_ABAProblem_Resolve_Demo {
        private static AtomicStampedReference<Integer> atomicStampedRef = new AtomicStampedReference<>(100, 0);

        public static void main(String[] args) throws InterruptedException {
            int originVersion = atomicStampedRef.getStamp();

            Thread t1 = new Thread(() -> {
                atomicStampedRef.compareAndSet(100, 101, originVersion, originVersion + 1);
                atomicStampedRef.compareAndSet(101, 100, originVersion + 1, originVersion + 2);
            });

            Thread t2 = new Thread(() -> {
                try {
                    // 使 t2 线程暂停1秒，确保 t1 线程完成了第一次修改
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boolean isSuccess = atomicStampedRef.compareAndSet(100, 101, originVersion, originVersion + 1);
                System.out.println("compareAndSet result aba:"+isSuccess);  // 输出 false，因为版本号已经被 t1 线程修改过
            });

            t1.start();
            t2.start();
            t1.join();
            t2.join();
        }
    }
